>char *string_array [NR_OF_STRINGS];
>string_array [i] = malloc (STRING_LENGTH);
Two things:
- string_array is a reserved name, so don't use it in your real code.
- STRING_LENGTH would imply strlen(myvar) would do the job. But it wouldn't, you must remember to include +1 for the null terminator.
Here's a working example:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define COUNT 5
int main(void)
{
char *my_ary[COUNT];
char buf[BUFSIZ];
int i;
for (i = 0; i < COUNT; i++)
{
/* You'd normally do error checking with this lot */
fgets(buf, sizeof buf, stdin);
my_ary[i] = malloc(strlen(buf)+1);
strcpy(my_ary[i], buf);
}
for (i = 0; i < COUNT; i++)
{
printf("%s", my_ary[i]);
free(my_ary[i]);
}
return 0;
}